package com.example.demo.tixiban;

/**
 * @author xujm
 * @version V2.4
 *
 * 两个链表从左到右分别是 低位到 高位，进行相加
 *   比如：
 *   2-4-5
 *   1-7
 *   =613
 *
 * @since 2.4.0 2022/2/12 11:26
 */
public class List_两个链表相加 {


    public static class Node {
        int val;
        Node next;
        Node(int x) { val = x; }
    }

    public static String add(Node head1,Node head2,int other,String result){

        if(head1!=null && head2!=null){
            int temp = head1.val + head2.val + other;
            if(temp >= 10){
                temp = temp % 10;
            result=add(head1.next,head2.next,1,result+temp);
            }else{
                result=add(head1.next,head2.next,0,result+temp);
            }
        }else if(head1!=null){
            int temp = head1.val + other;
            if(temp >= 10){
                temp = temp % 10;
                result=add(head1.next,null,1,result+temp);
            }else{
                result=add(head1.next,null,0,result+temp);
            }

        }else if(head2!=null){
            int temp = head2.val + other;
            if(temp >= 10){
                temp = temp % 10;
                result=add(null,head2.next,1,result+temp);
            }else{
                result=add(null,head2.next,0,result+temp);
            }
        }else{
            if(other>0){
                result+=other;
            }
        }
        return result;
    }

    public static void main(String[] args) {

        Node head1 = new Node(2);
        head1.next = new Node(4);
        head1.next.next = new Node(5);
        Node head2 = new Node(1);
        head2.next = new Node(7);

        String result = add(head1, head2, 0, "");
        StringBuffer sb = new StringBuffer(result);
        System.out.println(sb.reverse());

    }


}
